package com.example.demo.service;

import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.demo.DTO.LoginDto.LoginDto;
import com.example.demo.entity.User;
import com.example.demo.jwt.Jwt;
import com.example.demo.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.Date;

@Service
public class UserService {
    @Autowired
    private UserMapper userMapper;

    public String login(LoginDto loginDto){
        User user = userMapper.selectOne(new QueryWrapper<User>().eq("user_name",loginDto.getUserName()));
        if(user.getUserPassword().equals(DigestUtils.md5DigestAsHex(loginDto.getUserPassword().getBytes()))){
            return Jwt.encode(user.getUserId());
        }
        return "";
//        System.out.println("查询到的ID:"+user.getUserId());
    }

    public int register(User user){
        return userMapper.insert(user);
    }

    public User getUserInfo(String token){
        String userId = JWT.decode(token).getAudience().get(0);
        System.out.println(userId);
        return userMapper.selectOne(new QueryWrapper<User>()
                .select("user_name")
                .eq("user_id",userId));
    }
}
